package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : Bing
 * @Date 2023/3/2 18:52
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class AutoCreateMainTainTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {

        //解析消息
        VmStatusContract statusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);

        List<StatusInfo> collect = statusContract.getStatusInfo().stream()
                .filter(each -> !each.isStatus())
                .collect(Collectors.toList());

        VmVO vmInfo = vmService.getVMInfo(statusContract.getInnerCode());

        Integer leastUser = taskService.getLeastUser(vmInfo.getRegionId(), true);

        if (!CollectionUtils.isEmpty(collect)){
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0);
            taskViewModel.setInnerCode(statusContract.getInnerCode());
            taskViewModel.setUserId(leastUser);
            taskViewModel.setAssignorId(0);
            taskViewModel.setDesc(jsonMsg);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
            taskService.createTask(taskViewModel);
        }

    }

}
